#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Shopify 语言配置服务
负责处理用户语言配置的写入和发布功能
"""

import logging
from typing import Dict, Any, Optional
import requests

from app.utils.mysql_helper import MySQLHelper
from app.utils.error_handling import BadRequestError, InternalServerError
from app.conf.config import logger


class ShopifyLanguageConfigService:
    """
    Shopify 语言配置服务类
    提供用户语言配置的写入和发布功能
    """
    
    def __init__(self):
        """
        初始化服务
        """
        self.db_helper = MySQLHelper(auto_commit=True)
    
    def get_user_info_by_domain(self, shopify_domain: str) -> Dict[str, Any]:
        """
        根据shopify_domain获取用户信息
        
        Args:
            shopify_domain: 店铺域名
            
        Returns:
            Dict: 包含user_id和access_token的字典
            
        Raises:
            BadRequestError: 用户不存在时抛出
        """
        try:
            # 查询用户信息
            query = """
                SELECT id, access_token 
                FROM shopify_app.users 
                WHERE shop_domain = %s
            """
            result = self.db_helper.execute_query(query=query, params=(shopify_domain,))
            
            if not result:
                raise BadRequestError(f"用户不存在: {shopify_domain}")
            
            # 适配字典和元组两种结果格式
            if isinstance(result[0], dict):
                return {
                    'user_id': result[0]['id'],
                    'access_token': result[0]['access_token']
                }
            else:
                # 元组格式
                return {
                    'user_id': result[0][0],
                    'access_token': result[0][1]
                }
            
        except BadRequestError:
            raise
        except Exception as e:
            logger.error(f"获取用户信息失败: {str(e)}")
            raise InternalServerError(f"获取用户信息失败: {str(e)}")
    
    def get_shop_default_language(self, shopify_domain: str, access_token: str) -> str:
        """
        获取店铺默认语言
        
        Args:
            shopify_domain: 店铺域名
            access_token: Shopify API访问令牌
            
        Returns:
            str: 店铺默认语言代码
        """
        try:
            # 构建Shopify Store Information API URL
            url = f"https://{shopify_domain}/admin/api/2023-10/shop.json"
            
            # 设置请求头
            headers = {
                'X-Shopify-Access-Token': access_token,
                'Content-Type': 'application/json'
            }
            
            # 发送请求
            response = requests.get(url, headers=headers)
            response.raise_for_status()
            
            # 解析响应
            shop_data = response.json().get('shop', {})
            
            # 获取默认语言
            # Shopify的shop.json返回的是primary_locale字段，表示店铺的主要语言区域设置
            default_language = shop_data.get('primary_locale', 'en-US')
            
            logger.info(f"获取店铺默认语言成功: {shopify_domain} -> {default_language}")
            return default_language
            
        except requests.exceptions.RequestException as e:
            logger.error(f"获取店铺默认语言失败: {str(e)}")
            raise InternalServerError(f"获取店铺默认语言失败: {str(e)}")
        except Exception as e:
            logger.error(f"获取店铺默认语言异常: {str(e)}")
            raise InternalServerError(f"获取店铺默认语言异常: {str(e)}")
    
    def write_language_config(self, shopify_domain: str, target_language: str) -> Dict[str, Any]:
        """
        写入用户语言配置（使用插入更新操作）
        
        Args:
            shopify_domain: 店铺域名
            target_language: 目标语言
            
        Returns:
            Dict: 操作结果
        """
        try:
            # 验证参数
            if not shopify_domain or '.myshopify.com' not in shopify_domain:
                raise BadRequestError("无效的店铺域名")
            
            if not target_language:
                raise BadRequestError("目标语言不能为空")
            
            # 1. 获取用户信息
            user_info = self.get_user_info_by_domain(shopify_domain)
            user_id = user_info['user_id']
            access_token = user_info['access_token']
            
            # 2. 获取店铺默认语言
            shop_default_language = self.get_shop_default_language(shopify_domain, access_token)
            
            # 3. 使用INSERT...ON DUPLICATE KEY UPDATE语法实现基于完整主键的插入更新操作
            # 主键包括：user_id, shopify_domain, target_language
            insert_update_query = """
                INSERT INTO shopify_app.user_language_config 
                (user_id, shopify_domain, shop_default_language, target_language, is_published)
                VALUES (%s, %s, %s, %s, 0)
                ON DUPLICATE KEY UPDATE 
                    shop_default_language = VALUES(shop_default_language),
                    is_published = VALUES(is_published)
            """
            
            # 执行插入更新操作
            affected_rows = self.db_helper.execute_update(
                query=insert_update_query,
                params=(user_id, shopify_domain, shop_default_language, target_language)
            )
            
            # 判断是插入还是更新操作
            # affected_rows=1 表示插入，affected_rows=2 表示更新
            operation = "inserted" if affected_rows == 1 else "updated"
            
            logger.info(f"语言配置{operation}成功: user_id={user_id}, shopify_domain={shopify_domain}, target_language={target_language}")
            
            return {
                "is_success": 1,
                "message": f"语言配置{operation}成功",
                "user_id": user_id,
                "shopify_domain": shopify_domain,
                "shop_default_language": shop_default_language,
                "target_language": target_language
            }
            
        except BadRequestError:
            raise
        except Exception as e:
            logger.error(f"写入语言配置失败: {str(e)}")
            raise InternalServerError(f"写入语言配置失败: {str(e)}")
    
    def publish_language_config(self, shopify_domain: str, target_language: str) -> Dict[str, Any]:
        """
        发布用户特定语言配置
        实现逻辑：仅更新现有配置，将is_published字段设置为1
        
        Args:
            shopify_domain: 店铺域名
            target_language: 目标语言
            
        Returns:
            Dict: 操作结果
        """
        try:
            # 验证参数
            if not shopify_domain or '.myshopify.com' not in shopify_domain:
                raise BadRequestError("无效的店铺域名")
            
            if not target_language:
                raise BadRequestError("目标语言不能为空")
            
            # 获取用户ID和access_token
            user_info = self.get_user_info_by_domain(shopify_domain)
            user_id = user_info['user_id']
            access_token = user_info['access_token']
            
            # 获取店铺默认语言
            shop_default_language = self.get_shop_default_language(shopify_domain, access_token)
            
            # 先检查配置是否存在
            check_query = """
                SELECT COUNT(1) FROM shopify_app.user_language_config 
                WHERE user_id = %s AND shopify_domain = %s AND target_language = %s
            """
            check_params = (user_id, shopify_domain, target_language)
            result = self.db_helper.execute_query(check_query, check_params)
            
            if not result or (isinstance(result[0], dict) and result[0].get('COUNT(1)', 0) == 0) or (isinstance(result[0], (list, tuple)) and result[0][0] == 0):
                raise BadRequestError("语言配置不存在")
            
            # 仅执行更新操作，将is_published字段设置为1
            update_query = """
                UPDATE shopify_app.user_language_config 
                SET is_published = 1 
                WHERE user_id = %s AND shopify_domain = %s AND target_language = %s
            """
            
            # 执行更新操作
            affected_rows = self.db_helper.execute_update(
                query=update_query,
                params=(user_id, shopify_domain, target_language)
            )
            
            if affected_rows > 0:
                logger.info(f"语言配置发布成功: user_id={user_id}, shopify_domain={shopify_domain}, target_language={target_language}")
                return {
                    "is_success": 1,
                    "message": "语言配置发布成功",
                    "user_id": user_id,
                    "shopify_domain": shopify_domain,
                    "target_language": target_language,
                    "is_published": 1,
                    "shop_default_language": shop_default_language
                }
            else:
                raise InternalServerError("配置发布失败，请重试")
                
        except BadRequestError:
            raise
        except Exception as e:
            logger.error(f"发布语言配置失败: {str(e)}")
            raise InternalServerError(f"发布语言配置失败: {str(e)}")


# 创建服务实例
shopify_language_config_service = ShopifyLanguageConfigService()